package com.music.mysongs.fragment.option

import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.music.mysongs.R
import com.music.mysongs.adapter.DeleteRecyclerAdapter
import com.music.mysongs.data.MusicCreatorData
import com.music.mysongs.data.getApiMusicUidList
import com.music.mysongs.file.FileOP
import com.music.mysongs.helper.myActReadIntSPF
import com.music.mysongs.utils.myLog
import com.music.mysongs.web.CommonWebTask
import kotlin.collections.ArrayList

class CollectionFragment : Fragment() {
    private val mTAG = "CollectionFragment"
    private val codeCOLLECT = 1000
    private var collectData = ArrayList<MusicCreatorData.MusicList>()
    private var collectRecyclerView: RecyclerView? = null
    private val collectHandler: Handler = Handler {
        when (it.what) {
            codeCOLLECT -> {
                collectRecyclerView!!.adapter =
                    DeleteRecyclerAdapter(this.requireContext(), collectData)
            }
        }
        false
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initCollectData()
    }

    private fun initCollectData() {
        val uid = myActReadIntSPF(this.activity, "spfUserId")
        val musicTask = CommonWebTask()
        musicTask.url = getApiMusicUidList(uid!!)
        musicTask.setCallbackHandler { innerData ->
            val data = Gson().fromJson(innerData, MusicCreatorData.MusicData::class.java)
            if (data.code == 20000) {
                collectData = data.data!!
                val msg = Message()
                msg.what = codeCOLLECT
                collectHandler.sendMessage(msg)
            } else {
                myLog("$mTAG: $innerData")
            }
        }
        musicTask.execute()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        val v = inflater.inflate(R.layout.fragment_collection, container, false)
        collectRecyclerView = v.findViewById(R.id.recyclerViewCollect_option)
        collectRecyclerView!!.layoutManager = LinearLayoutManager(this.context)
        return v
    }
}